<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="公告标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入公告标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="公告分类" prop="category">
        <el-select v-model="queryParams.category" placeholder="请选择公告分类" clearable>
          <el-option
            v-for="dict in announce_category"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="公告状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择公告状态" clearable>
          <el-option
            v-for="dict in announce_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['announcement:announcement:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['announcement:announcement:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['announcement:announcement:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['announcement:announcement:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Position"
          :disabled="multiple"
          @click="handleSend"
          v-hasPermi="['announcement:announcement:publish']"
        >发送</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="announcementList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="公告ID，主键" align="center" prop="id" /> -->
      <el-table-column label="公告标题" align="center" prop="title" />
      <el-table-column label="公告分类" align="center" prop="category">
        <template #default="scope">
          <dict-tag :options="announce_category" :value="scope.row.category"/>
        </template>
      </el-table-column>
      <el-table-column label="公告范围" align="center" prop="scope">
        <template #default="scope">
          <dict-tag :options="announce_scope" :value="scope.row.scope"/>
        </template>
      </el-table-column>
      <el-table-column label="公告状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="announce_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="已读数量" align="center" prop="readCount"/>
      <el-table-column label="未读数量" align="center" prop="unreadCount"/>
      <el-table-column label="发布时间" align="center" prop="publishTime" width="150">
        <template #default="scope">
          <span>{{ parseTime(scope.row.publishTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column
  label="公告内容"
  align="center"
  prop="content"
  :formatter="formatContent"
/>
      <el-table-column label="记录创建时间" align="center" prop="createdAt" width="150">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="记录最后更新时间" align="center" prop="updatedAt" width="150">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['announcement:announcement:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['announcement:announcement:remove']">删除</el-button>
          <el-button link type="primary" icon="Position" @click="handleSend(scope.row)" v-hasPermi="['announcement:announcement:edit']">发送</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改公告管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="announcementRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入公告标题" />
        </el-form-item>
        <el-form-item label="公告分类" prop="category">
          <el-select v-model="form.category" placeholder="请选择公告分类">
            <el-option
              v-for="dict in announce_category"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="公告范围" prop="scope">
          <el-select v-model="form.scope" placeholder="请选择公告范围">
            <el-option
              v-for="dict in announce_scope"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="公告状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择公告状态">
            <el-option
              v-for="dict in announce_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发布时间" prop="publishTime">
          <el-date-picker clearable
            v-model="form.publishTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择发布时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="公告内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Announcement">
import { listAnnouncement, getAnnouncement, delAnnouncement, addAnnouncement, updateAnnouncement, publishAnnouncement } from "@/api/announcement/announcement"
import { ref } from "vue"

const { proxy } = getCurrentInstance()
const { announce_scope, announce_status, announce_category } = proxy.useDict('announce_scope', 'announce_status', 'announce_category')

const announcementList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
//记录员工总数
const employeeCount = ref(0)


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: null,
    category: null,
    status: null,
  },
  rules: {
    title: [
      { required: true, message: "公告标题不能为空", trigger: "blur" }
    ],
    category: [
      { required: true, message: "公告分类，如：通知、公告、新闻等不能为空", trigger: "change" }
    ],
    scope: [
      { required: true, message: "公告范围：全公司/部门/个人不能为空", trigger: "change" }
    ],
    status: [
      { required: true, message: "公告状态：草稿/已发布/已归档不能为空", trigger: "change" }
    ],
    content: [
      { required: true, message: "公告内容不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)



/** 查询公告管理列表 */
function getList() {
  loading.value = true
  listAnnouncement(queryParams.value).then(response => {
    announcementList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    title: null,
    category: null,
    publisherId: null,
    scope: null,
    status: null,
    readCount: null,
    unreadCount: null,
    publishTime: null,
    content: null,
    delFlag: null,
    createdAt: null,
    updatedAt: null
  }
  proxy.resetForm("announcementRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加公告管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getAnnouncement(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改公告管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["announcementRef"].validate(valid => {
    if (valid) {
      form.value.publisherId = localStorage.getItem("userId")
      if (form.value.id != null) {
        updateAnnouncement(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addAnnouncement(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除公告管理编号为"' + _ids + '"的数据项？').then(function() {
    return delAnnouncement(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('announcement/announcement/export', {
    ...queryParams.value
  }, `announcement_${new Date().getTime()}.xlsx`)
}

/** 发送按钮操作 */
function handleSend(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认发送公告编号为"' + _ids + '"的数据项？').then(function() {
    return publishAnnouncement(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("发送成功")
  }).catch(() => {})
}

getList()

const formatContent = (row) => {
  if (!row.content) return ''
  return row.content.length > 10 ? row.content.slice(0, 10) + '...' : row.content
}


//webSocket
let socket = null
const announcementId = ref(null)

function connectWebSocket() {
  const wsUrl = 'ws://localhost:8080/ws/announcement'
  socket = new WebSocket(wsUrl)

  socket.onopen = function() {
    console.log('WebSocket连接成功');    
  }

  socket.onmessage = function(event) {
    const data = JSON.parse(event.data)
    announcementId.value = data.announcementId
    //遍历公告集合找到id为announcementId的公告
    const index = announcementList.value.findIndex(item => {
      return String(item.id) === String(announcementId.value)
    })
    if (index !== -1) {
      // 使用新的数组确保响应式更新
      const updatedList = [...announcementList.value]
      updatedList[index] = {
        ...updatedList[index],
        readCount: updatedList[index].readCount + 1,
        unreadCount: updatedList[index].unreadCount - 1
      }
      // 重新赋值触发响应式更新
      announcementList.value = updatedList
    } else {
      console.warn(`未找到 ID 为 ${announcementId.value} 的公告`)
    }
  }

  socket.onclose = () => {
    console.log('WebSocket disconnected')
    // 自动重连
    setTimeout(connectWebSocket, 3000)
  }
}

onMounted(() => {
  connectWebSocket()
})
  
//页面关闭断开websocket连接
onBeforeUnmount(() => {
  if (socket) {
    console.log('断开WebSocket连接')
    socket.close()
  }
})

</script>
